const fs = require('fs')
const path = require('path')
const packagesDir = path.resolve(__dirname, '../packages')
const files = fs.readdirSync(packagesDir)
const { prompt } = require('enquirer')
const vueCli = require('./vue-cli')

const webapp_choices = []

/**
 * 收集网站应用
 * @param {String} processingDirectory 当前处理的目录
 * @param {String} files 遍历文件目录列表
 */
const collectWebapp = function(processingDirectory, files) {
  files.forEach(shortname => {
    // 非目录的不处理
    if (!fs.statSync(path.join(processingDirectory, shortname)).isDirectory()) return
    const pkgPath = path.join(processingDirectory, shortname, `package.json`)
    const pkgExists = fs.existsSync(pkgPath)
    if (pkgExists) {
      const pkg = require(pkgPath)
      const buildOptions = pkg.buildOptions
      if (buildOptions && buildOptions.target && buildOptions.target === 'web') {
        const appRootDir = path
          .join(processingDirectory, shortname)
          .replace(packagesDir, '')
          .trimStart()
          .substr(1)
        webapp_choices.push(appRootDir)
      }
    } else {
      const monorepoPath = path.join(processingDirectory, shortname, `.monorepo`)
      const isMonorepo = fs.existsSync(monorepoPath)
      if (isMonorepo) {
        const packageDir = path.join(processingDirectory, shortname)
        const directories = fs.readdirSync(packageDir)
        collectWebapp(packageDir, directories)
      }
    }
  })
}

collectWebapp(packagesDir, files)

async function main() {
  const { webapp } = await prompt({
    type: 'select',
    name: 'webapp',
    message: 'Select a webapp server that you will be starting（请选择你要启动的网站）...',
    choices: webapp_choices
  })

  const appRootDir = path.resolve(__dirname, '../packages', webapp)
  vueCli.exec(appRootDir, 'serve')
}

main().catch(err => {
  console.error(err)
})
